<template>
  <div class="about">
    <!-- <div style="display: flex;justify-content: center;align-items: center;">
        <el-form label-position="left" label-width="120px" :model="s3Clent" style="width:500px">
            <el-form-item label="endpoint">
                <el-input v-model="s3Clent.endpoint"></el-input>
            </el-form-item>
            <el-form-item label="region">
                <el-input v-model="s3Clent.region"></el-input>
            </el-form-item>
            <el-form-item label="signatureVersion">
                <el-input v-model="s3Clent.signatureVersion"></el-input>
            </el-form-item>
            <el-form-item label="accessKeyId">
                <el-input v-model="s3Clent.credentials.accessKeyId"></el-input>
            </el-form-item>
            <el-form-item label="secretAccessKey">
                <el-input v-model="s3Clent.credentials.secretAccessKey"></el-input>
            </el-form-item>
        </el-form>
    </div> -->
    <input multiple v-show="false" ref="fileRef" type="file" @change="inputFile">
    <el-button type="primary" @click="upload()">点击上传文件</el-button>

    <div v-for="f in fileList" :key="f.key">
      <div style="margin-top:50px;display: flex;align-items: center;justify-content: center;" v-if="f.show">
        <div style="margin-right:20px;font-size:15px;font-weight:60">
          {{ f.key }}
        </div>
        <el-progress :percentage="f.percentage" style="width:500px"></el-progress>
        <div style="margin-left:20px">
          <span v-if="f.status == 'err'" style="color:#F56C6C">上传错误</span>
          <span v-else-if="f.status == 'same key'" style="color:#F56C6C">同名文件</span>
          <span v-else-if="f.status == 'success'" style="color:#67C23A">上传成功</span>
          <span v-else-if="f.status == 'suspend'" style="color:#409EFF">已暂停</span>
        </div>
        <div style="margin-left:20px">
          <!-- 暂停按钮 -->
          <el-button type="primary" icon="el-icon-video-pause" circle v-if="f.status === 'wait'"
            @click="suspendButton(f)"></el-button>
          <!-- 继续按钮 -->
          <el-button type="primary" icon="el-icon-video-play" circle v-if="f.status === 'suspend'"
            @click="continuedButton(f)"></el-button>
          <!-- 取消按钮 -->
          <el-button type="danger" icon="el-icon-close" circle v-if="f.status === 'suspend' || f.status === 'err'"
            @click="cancelButton(f)"></el-button>
          <!-- 重试按钮 -->
          <el-button type="primary" icon="el-icon-refresh-right" circle v-if="f.status === 'err'"
            @click="continuedButton(f)"></el-button>
        </div>
      </div>
    </div>
    <!-- video -->
    <video controls class="videoItem" @durationchange="durationchange" ref="video" id="video" crossorigin="anonymous" @pause="palyPause" @canplay="canplay" @timeupdate="onTimeupdate">
      <source :src="options.src"/>
      <track
        v-for="(item,index) in cationArr"
        :key="index"
        :label="item.label"
        kind="subtitles"
        :srclang="item.lang"
        :src="item.src"
        :default="item.default"
      />
    </video>
    
    <!-- time slider -->
    <div class="sliderBox">
      <div class="scrollbox">
        <!-- <div class="sliderTop">

        </div>
        <div class="sliderCenter">

        </div>
        <div class="sliderBottom">

        </div> -->
        <TimeLineCanvas
          :height="timelineData.height"
          :timeRange="timelineData.timeRange"
          :startMeddleTime="timelineData.startMeddleTime"
          :markTime="timelineData.markTime"
          @click="clickCanvas"
        ></TimeLineCanvas>
      </div>
    </div>
    
    <!-- <el-button id="button" type="primary" @click="screenshot">截图</el-button> -->
    <el-button id="button" type="primary" @click="createFPS">截图</el-button>
    <img class="img" v-for="item in videoFrames" :key="item" :src="item">

  </div>
</template>

<script>
// import scVideo from '@/components/scVideo'

// video for hls
import "vue3-video-play/dist/style.css";
import { videoPlay } from "vue3-video-play";
import Hls from 'hls.js';

// time slider
import TimeLineCanvas from "../../components/timeLine.vue"
// 分片上传
import { init, fileChange, getWorker, cancel } from "@/utils/awsSDK.js"
const s3ClientObj = {
  development: {
    endpoint: "https://s3.ap-northeast-1.amazonaws.com/storage.dev.mov.movie/temp", //存储文件的服务器的地址，无端口
    s3ForcePathStyle: true,
    signatureVersion: 'v4',
    region: 'ap-northeast-1',
    forcePathStyle: true,
    credentials: {
      accessKeyId: "AKIARHG2KXXR25WAOTML",
      secretAccessKey: "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",
    }
  },
  production: {
    endpoint: "https://s3.ap-northeast-1.amazonaws.com/storage.dev.mov.movie/temp", //存储文件的服务器的地址，无端口
    s3ForcePathStyle: true,
    signatureVersion: 'v4',
    region: 'ap-northeast-1',
    forcePathStyle: true,
    credentials: {
      accessKeyId: "AKIARHG2KXXR25WAOTML",
      secretAccessKey: "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",
    }
  }
}

// 抽帧
import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg';
const ffmpeg = createFFmpeg({
  corePath: "js/ffmpeg-core.js",
  log: true
});
console.log('load',ffmpeg)
// async function load(){
//   let res = await ffmpeg.load()
//   console.log('加载完成',res);
// }
// load()
// if(!ffmpeg.isLoaded()) {
//   ffmpeg.load().catch((err) => {
//     console.log('加载失败',err);
//   });
// }



export default {
  components: {
    // scVideo,
    videoPlay,
    TimeLineCanvas
  },
  data() {
    return {
      // 字幕
      cationArr: [
        {
          label: 'English',
          lang: 'en',
          src: '',
          default: false
        },
        {
          label: 'Japanese',
          lang: 'ja',
          src: '',
          default: true
        },
        {
          label: '中文简体',
          lang: 'zh',
          src: '',
          default: false
        },
        {
          label: '中文繁体',
          lang: 'zt',
          src: '',
          default: false
        }
      ],
      options: {
        playbackRate: [0.5, 0.75, 1, 1.5, 2], //传入倍速可选数组
        volume: 1,
        src: 'https://s3.ap-northeast-1.amazonaws.com/storage.dev.mov.movie/temp/1712740502127/1712740502127_test.mp4'
      },
      liveUrl: 'https://s3.ap-northeast-1.amazonaws.com/storage.dev.mov.movie/temp/1712740502127/1712740502127_test.mp4',
      hls: null,

      // 时间轴
      timelineData: {
        height: 150,
        startMeddleTime: "",
        timeRange: ["", ""],
        markTime: [
          {
            beginTime: "2024-04-11 00:01:00",
            endTime: "2024-04-11 00:02:00",
            bgColor: "greyColor",
            text: "我有一头小毛驴从来也不骑0-我有一头小毛驴从来也不骑1-我有一头小毛驴从来也不2-我有一头小毛驴从来也不骑3-我有一头小毛驴从来也不骑4",
          },
          {
            beginTime: "2024-04-11 00:05:00",
            endTime: "2024-04-11 00:08:00",
            bgColor: "greyColor",
            text: "非法闯入",
          },
          {
            beginTime: "2024-04-11 00:10:00",
            endTime: "2024-04-11 00:14:00",
            bgColor: "greyColor",
            text: "故障",
          },
        ]
      },

      fileList: [],
      bucketList: [],
      key: '',
      videoFrames: [], //视频帧
      ffVideo: {
        name: '',
        file: null,
        duration: 0
      },
      files: null
    }
  },
  mounted() {
    console.log('环境', process.env.NODE_ENV)
    init(s3ClientObj[process.env.NODE_ENV])
    
    // 初始化视频
    // this.formatData(this.enBlob,1,'en')
    try{
      this.$nextTick(()=>{
        this.hls = new Hls();
        // this.hls.loadSource(this.liveUrl);
        // this.hls.attachMedia(this.$refs.video);

        
        // this.defaultData.timer = setInterval(() => {
        //   this.defaultData.time2 += 1000
        //   Timeline2.value.setTime(this.defaultData.time2)
        // }, 1000)
      })
    }catch(e){
      console.log(e)
    }
  },
  methods: {
    // 生成帧画面
    async createFPS(){
			let video=document.querySelector('#video');
			let width = 500;
			let height = 500 / (video.videoWidth / video.videoHeight);
      try {
        await ffmpeg.load()
        let { name, file, duration } = this.ffVideo;
        ffmpeg.FS("writeFile", name, await fetchFile(file));
        // 计算每秒需要抽的帧数
        let step = Math.ceil(20 / duration),
          allNum = Math.floor(step * duration);
        console.log("step", step, allNum,width,height);
        await ffmpeg.run(
          "-i",
          name,
          "-r",
          `${step}`,
          "-ss",
          "0",
          "-vframes",
          `${allNum}`,
          "-f",
          "image2",
          "-s",
          `500*300`,
          "image-%02d.png"
        );
        for (let i = 0; i < allNum; i++) {
          let temp = i + 1;
          if (temp < 10) {
            temp = "0" + temp;
          }
          let buffer = ffmpeg.FS("readFile", "image-"+temp+".png")
          if(i % 5 == 0 && this.videoFrames.length < 3)this.videoFrames.push('data:image/png;base64,'+this.arrayBufferToBase64(buffer));
        }
        console.log('生成帧动画',this.videoFrames)
        // this.$emit("frame", this.videoFrames);
      } catch (err) {
        console.warn(err)
      }
    },
    // buffer转base64
    arrayBufferToBase64 (buffer) {
      var binary = ''
      var bytes = new Uint8Array(buffer)
      var len = bytes.byteLength
      for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i])
      }
      return window.btoa(binary)
    },
    screenshot(){
      // let button=document.querySelector('#button');
			let video=document.querySelector('#video');
			let img=document.querySelector('#img');
      console.log(111,video.videoWidth,video.videoHeight)
			// let captureImage=function(){
				let canvas=document.createElement('canvas');
				canvas.width = 720;
				canvas.height = 720 / (video.videoWidth / video.videoHeight);
				let ctx=canvas.getContext('2d');
				ctx.drawImage(video,0,0,canvas.width,canvas.height);
				//此时我们已经有图片了(表现为canvas标签)，但是我们需要插入到img标签中！
				// let img=document.createElement('img');
				// canvas.toDataURL(type, encoderOptions); -> 图片格式，图片质量
				img.src=canvas.toDataURL('image/png');
				// document.body.appendChild(img);
				// mxcimg.style.display="none";
			// };
      // button.addEventListener('click',function(){
			// 	mxcimg.style.display="block";
				
			// 	video.addEventListener('loadeddata',captureImage);
			// });
    },
    // 时间更新
    onTimeupdate(){
      let video = this.$refs.video;
      this.timelineData.startMeddleTime = '2024-04-11 ' + this.$TOOL.formateTime(video.currentTime)
      // console.log('时间更新',e)
    },
    // 点击时间轴
    clickCanvas(e){
      this.$nextTick(()=>{
        let video = this.$refs.video;
        if(typeof(e) == 'object') return;
        video.currentTime = this.$TOOL.turnMillSecond(this.$TOOL.dateFormat(e,'hh:mm:ss'),true)
        console.log('点击获取时间',e,video.currentTime)
      })
    },
    canplay(){
      let video = this.$refs.video;
      this.timelineData.startMeddleTime = '2024-04-11 ' + this.$TOOL.formateTime(video.currentTime)
      this.timelineData.timeRange[0] = '2024-04-11 00:00:00'
      this.timelineData.timeRange[1] = '2024-04-11 '+this.$TOOL.formateTime(video.duration)
      // video.currentTime = 100;
      setTimeout(()=>{

        // this.screenshot()
      },500)
      console.log('canplay',video.currentTime)
    },
    // 视频暂停
    palyPause(){
      console.log('播放暂停')
      this.getVideoTime();
    },
    getVideoTime(){
      try {
        let video = this.$refs.video;
        this.timelineData.startMeddleTime = '2024-04-11 ' + this.$TOOL.formateTime(video.currentTime)
        // for(let i=0;i<this.zmList.length;i++){
        //   if( video.currentTime >= this.zmList[i].stimeStamp && video.currentTime < this.zmList[i].etimeStamp){
        //     this.current = i;
        //     console.log("Current time: " + video.currentTime,this.zmList[i]); 
        //   }
        // }
      } catch(e) {console.warn(e)}
    },

    async continuedButton(file) {
      file.needSuspend = false;
      file.status = 'wait';
      const isInQueue = getWorker(file.file);
      console.log("isInQueue", isInQueue)
      if (isInQueue === false) {
        //如果任务队列中没有这个文件上传任务，那么就加入到任务队列中
        fileChange({ fileList: [file], bucket: file.bucket, changeStatus: this.changeStatus, getSuspend: this.getSuspend, changeSharding: this.changeSharding });
      }

    },
    async cancelButton(f) {
      await cancel({ bucket: f.bucket, file: f.file });
      this.fileList = this.fileList.filter(e => {
        return e.key !== f.key;
      });
    },
    upload() {
      this.$refs.fileRef.dispatchEvent(new MouseEvent('click'));
    },
    inputFile(event) {
      this.files = event.target.files;
      let addFile = [];
      console.log('上传文件', this.files,addFile)
      
      this.ffVideo.name = this.files[0].name;
      this.ffVideo.duration = 10;
      this.ffVideo.file = this.files[0];
      // for (let i = 0; i < this.files.length; i++) {
      //   let bucketName = '' + new Date().getTime() + '';
      //   if (this.bucketList.indexOf(bucketName) >= 0) bucketName = bucketName + i
      //   let key = bucketName + "_test.mp4";
      //   this.bucketList.push(bucketName)
      //   this.fileList.push({
      //     percentage: 0,
      //     status: 'wait',
      //     show: true,
      //     file: this.files[i],
      //     needSuspend: false,
      //     sharding: [],//分片数组
      //     shardSize: 5 * 1024 * 1024,//每个分片的大小
      //     key: key,
      //     bucket: bucketName
      //   });
      //   addFile.push({
      //     percentage: 0,
      //     status: 'wait',
      //     show: true,
      //     file: this.files[i],
      //     needSuspend: false,
      //     sharding: [],//分片数组
      //     shardSize: 5 * 1024 * 1024,//每个分片的大小
      //     key: key,
      //     bucket: bucketName
      //   });
      // }
      // fileChange({ fileList: addFile, bucket: '', changeStatus: this.changeStatus, getSuspend: this.getSuspend, changeSharding: this.changeSharding })
    },
    //暂停
    suspendButton(file) {
      file.needSuspend = true;
      file.status = 'suspend';
    },
    //修改状态
    changeStatus(key, val) {
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].key == key) {
          this.fileList[i].status = val;
          if (val === 'success') {
            this.fileList[i].percentage = 100;
          }
          break;
        }
      }
    },
    //修改分片数组
    changeSharding(key, shard) {
      console.log(shard)
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].key === key) {
          this.fileList[i].sharding = shard;
          //改变进度条
          let size = 0;
          for (let j = 0; j < shard.length; j++) {
            size += shard[j].Size;
          }
          this.fileList[i].percentage = ((size / this.fileList[i].file.size) * 100).toFixed(1) - 0;
          return;
        }
      }
    },
    //获取该文件是否需要暂停
    getSuspend(key) {
      let suspend = this.fileList.filter(e => {
        return e.key === key;
      });
      if (suspend.length != 0) {
        return suspend[0].needSuspend;
      }
      return false;
    }
  }
}
</script>

<style>
.about {
  margin-bottom: 200px;
}
.videoItem {
  width: 100%;
  max-height: 800px;
}
.sliderBox {
  position: fixed;
  bottom: 10px;
  width: -webkit-fill-available;
}
.img {
  width: 500px;
  object-fit: contain;
}

</style>